<?php

namespace App\Api\Controllers\v1;

use App\Api\Models\Config;
use App\Http\Controllers\ApiController;
use App\Http\Requests\GoodPayRequest;
use App\Http\Response\ApiResponse;
use App\Models\Appraise;
use App\Models\Banner;
use App\Models\Category;
use App\Models\PaymentOrder;
use App\Models\User;
use App\Models\UserAddress;
use App\Services\GoodService;
use App\Services\OrderService;
use hg\apidoc\annotation as Apidoc;

/**
 * 商城接口
 * @Apidoc\Group("common")
 * @Apidoc\Sort(1)
 */
class GoodsController extends ApiController
{

    /**
     * 首页接口
     * @Apidoc\Url("/api/v1/goods/index")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("banners", type="array", desc="轮播图信息")
     * @Apidoc\Returned("items", type="array", desc="商品分类")
     */
    public function index(): ApiResponse
    {
        $data['banners'] = Banner::getList(2);
        foreach ($data['banners'] as $banner){
            $banner->image = cdn_url($banner->image);
        }
        $items = Category::getList();
        $items = array_merge([['id'=>0,'name'=>'全部']],$items->toArray());
        $data['items'] = $items;
        return $this->response()->data($data);
    }

    /**
     * 获取商品列表
     * @Apidoc\Url("/api/v1/goods/list")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("category_id",type="int",default="0",desc="分类ID,默认0查询全部")
     * @Apidoc\Query(ref="queryPage")
     * @Apidoc\Returned(ref="listResult")
     * @return ApiResponse
     */
    public function list(): ApiResponse
    {
        return $this->response()->success("ok")->data(GoodService::getList());
    }


    /**
     * 商品详情
     * @Apidoc\Url("/api/v1/goods/detail")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("id", type="int", require="true", desc="商品ID")
     * @Apidoc\Returned("detail", type="object", desc="商品详情")
     */
    public function detail(): ApiResponse
    {
        $id = $this->request->input("id",0);
        $user_id = $this->user_id;
        $detail = GoodService::getDetail($id,$user_id);
        return $this->response()->success("ok")->data(['detail'=>$detail]);
    }


    /**
     * 获取快递运费
     * @Apidoc\Url("/api/v1/goods/courier_fee")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("price", type="float", desc="快递运费")
     */
    public function courier_fee(): ApiResponse
    {
        $courier_fee = Config::getName("courier_fee");
        $address = UserAddress::whereUserId($this->user_id)->where("is_default",1)->first();
        return $this->response()->success("ok")->data([
            'price'=>floatval($courier_fee),
            'address'=>$address
        ]);
    }

    /**
     * 商品购买支付
     * @Apidoc\Url("/api/v1/goods/pay")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("pay_way", type="int", require="true", desc="支付方式:0=余额支付,1=微信支付",  default="0")
     * @Apidoc\Param("method", type="int", require="true", desc="收货方式:0=快递配送,1=到店自提",  default="0")
     * @Apidoc\Param("cars", type="array", require="true", desc="购买信息",  default="",
     *      @Apidoc\Param("good_id", type="int", require="true", desc="商品ID",  default=""),
     *      @Apidoc\Param("good_number", type="int", require="true", desc="商品数量",  default=""),
     * )
     * @Apidoc\Param("address", type="object", require="true", desc="地址相关信息",  default="",
     *     @Apidoc\Param("shop_id", type="int", require="true", desc="门店ID,到店自提必传",  default=""),
     *     @Apidoc\Param("area", type="string", require="true", desc="所在地区: 省/市/区 ",  default=""),
     *     @Apidoc\Param("address", type="string", require="true", desc="详细地址 ",  default=""),
     *     @Apidoc\Param("name", type="string", require="true", desc="名称",  default=""),
     *     @Apidoc\Param("phone", type="string", require="true", desc="电话",  default=""),
     * )
     * @Apidoc\Returned("payInfo",desc="余额支付时,返回false, 微信支付时返回微信支付信息")
     * @Apidoc\Returned("out_trade_no", type="string",desc="订单号")
     */
    public function pay(GoodPayRequest $request){
        $params = $request->validated();
        if ($params['method']){
            $shop_id = $params['address']['shop_id']??null;
            if (!$shop_id){
                return $this->response()->error("请选择自提门店");
            }
            $params['shop_id'] = $shop_id;
        }else{
            $params['shop_id'] = 0;
        }
        $params['courier_fee'] = Config::getName("courier_fee");
        return $this->wechatPay(function ($out_trade_no,$openid,$user_id) use($params) {
            $params = GoodService::handleCars($params,$user_id);
            $params['out_trade_no'] = $out_trade_no;
            $amount = collect($params['cars'])->pluck("total_price")->sum();
            if ($params['method']){
                $params['courier_fee'] = 0;
            }else{
                $amount += floatval($params['courier_fee']);
            }
            $params['amount'] = $amount;
            if ($params['pay_way']){
                OrderService::addGoodOrder($params);
                $notify_url = route("api.v1.notify",['type'=>1]);
                $body = "购买商品";
                return PaymentOrder::getPayData($openid, $body, $out_trade_no, $amount, $notify_url);
            }else{
                $user = User::find($user_id);
                if ($user->money<$amount){
                    return [
                        'response'=>$this->response()->error("余额不足!")
                    ];
                }
                OrderService::addGoodOrder(  $params);
                return [
                    'response'=> $this->response()->success('下单成功')->data(['out_trade_no'=>$out_trade_no,'payInfo'=>false])
                ];
            }
        });
    }
}
